<template>
  <div class="app-container">
    <!-- 查询条件区域 -->
    <el-card>
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="工单模板">
              <el-select v-model="queryParams.workOrderTemplateId" placeholder="请选择工单模板" clearable filterable
                style="width: 100%">
                <el-option v-for="item in workOrderTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="构筑物">
              <el-select v-model="queryParams.structureId" placeholder="请选择构筑物" clearable filterable
                style="width: 100%">
                <el-option v-for="item in structureOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="任务类型">
              <el-select v-model="queryParams.taskType" placeholder="请选择任务类型" clearable style="width: 100%">
                <el-option v-for="item in taskTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="mt-1">
      <el-button type="primary" icon="Plus" @click="handleAdd">新增任务</el-button>
      <el-button type="success" icon="Connection" @click="showBatchDialog">批量关联</el-button>
      <el-table :data="taskList" border v-loading="loading" class="mt-2" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="taskName" label="任务名称" width="180" align="center" />
        <el-table-column prop="taskType" label="任务类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag>{{ getTaskTypeLabel(row.taskType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="taskDescription" label="任务描述" align="center" />
        <el-table-column prop="options" label="选项内容" width="150" align="center" />
        <el-table-column prop="isRequired" label="是否必填" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isRequired === 1 ? 'success' : 'info'">
              {{ row.isRequired === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sequence" label="任务顺序" width="100" align="center" >
          <template #default="{ row }">
            <el-tag>{{ getName(taskTypeOptions,row.sequence , 'dictValue' ,'dictLabel') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="截止日期" width="120" align="center" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleUpdate(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px">
      <el-form ref="taskFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="工单模板">
              <el-select v-model="form.workOrderTemplateId" placeholder="请选择工单模板" clearable filterable
                style="width: 100%">
                <el-option v-for="item in workOrderTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
        <el-form-item label="构筑物">
          <el-select v-model="form.structureId" placeholder="请选择构筑物" clearable filterable style="width: 100%">
            <el-option v-for="item in structureOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-select v-model="form.taskType" placeholder="请选择任务类型" style="width: 100%">
            <el-option v-for="item in taskTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述" prop="taskDescription">
          <el-input v-model="form.taskDescription" type="textarea" :rows="3" placeholder="请输入任务描述" />
        </el-form-item>
        <el-form-item label="选项内容" prop="options">
          <el-input v-model="form.options" type="textarea" :rows="2" placeholder="请输入选项内容，多个选项用逗号分隔" />
        </el-form-item>
        <el-form-item label="是否必填" prop="isRequired">
          <el-radio-group v-model="form.isRequired">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务顺序" prop="sequence">
          <el-input-number v-model="form.sequence" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="截止日期" prop="dueDate">
          <el-date-picker v-model="form.dueDate" type="date" placeholder="选择截止日期" value-format="YYYY-MM-DD"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 批量关联对话框 -->
    <el-dialog v-model="batchDialog.visible" title="批量关联模板" width="500px">
      <el-form>
        <el-form-item label="选择模板" required>
          <el-select v-model="batchDialog.workOrderTemplateId" placeholder="请选择工单模板" style="width: 100%">
            <el-option v-for="item in workOrderTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchAssociate">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getTaskTypeList,
  getWorkOrderTypeList,
  getStructureList,
  listWorkOrderTask,
  getWorkOrderTask,
  addWorkOrderTask,
  updateWorkOrderTask,
  deleteWorkOrderTask,
  batchAssociateTemplate
} from '@/api/prod_operate/sys_setting/work_order/work_task'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  workOrderTemplateId: undefined,
  structureId: undefined,
  taskType: undefined
})

// 表单数据
const form = ref({
  taskId: undefined,
  workOrderTemplateId: undefined,
  structureId: undefined,
  taskName: '',
  taskType: '',
  taskDescription: '',
  options: '',
  isRequired: 1,
  sequence: 1,
  dueDate: '',
  remark: ''
})

// 对话框控制
const dialog = reactive({
  visible: false,
  title: ''
})

// 批量关联对话框
const batchDialog = reactive({
  visible: false,
  workOrderTemplateId: undefined
})

// 下拉选项数据
const taskTypeOptions = ref([])
const workOrderTypeOptions = ref([])
const structureOptions = ref([])

// 表格数据
const taskList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const taskFormRef = ref()

// 表单验证规则
const rules = reactive({
  taskName: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  taskType: [
    { required: true, message: '请选择任务类型', trigger: 'change' }
  ],
  taskDescription: [
    { required: true, message: '请输入任务描述', trigger: 'blur' }
  ],
  isRequired: [
    { required: true, message: '请选择是否必填', trigger: 'change' }
  ],
  sequence: [
    { required: true, message: '请输入任务顺序', trigger: 'blur' }
  ]
})

// 初始化加载数据
onMounted(() => {
  fetchDropdownOptions()
  fetchTaskList()
})

// 获取下拉选项数据
const fetchDropdownOptions = async () => {
  try {
    const [taskTypesRes, workOrderTypesRes, structuresRes] = await Promise.all([
      getTaskTypeList(),
      getWorkOrderTypeList(),
      getStructureList()
    ])

    taskTypeOptions.value = taskTypesRes.data || []
    workOrderTypeOptions.value = workOrderTypesRes.data || []
    structureOptions.value = structuresRes.data || []

  } catch (error) {
    console.error('获取下拉选项失败:', error)
    ElMessage.error('获取下拉选项失败')
  }
}

// 获取任务类型标签
const getTaskTypeLabel = (value) => {
  const item = taskTypeOptions.value.find(item => item.dictValue === value)
  return item ? item.dictLabel : value
}

// 获取工单任务列表
const fetchTaskList = async () => {
  try {
    loading.value = true
    const res = await listWorkOrderTask(queryParams)
    taskList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取工单任务列表失败:', error)
    ElMessage.error('获取工单任务列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchTaskList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.workOrderTemplateId = undefined
  queryParams.structureId = undefined
  queryParams.taskType = undefined
  fetchTaskList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchTaskList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchTaskList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增按钮
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增工单任务'
  form.value = {
    taskId: undefined,
    workOrderTemplateId: queryParams.workOrderTemplateId,
    structureId: queryParams.structureId,
    taskName: '',
    taskType: '',
    taskDescription: '',
    options: '',
    isRequired: 1,
    sequence: 1,
    dueDate: '',
    remark: ''
  }
}

// 编辑按钮
const handleUpdate = async (row) => {
  try {
    const res = await getWorkOrderTask(row.taskId)
    form.value = res.data
    dialog.visible = true
    dialog.title = '编辑工单任务'
  } catch (error) {
    console.error('获取工单任务详情失败:', error)
    ElMessage.error('获取工单任务详情失败')
  }
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除任务 "${row.taskName}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deleteWorkOrderTask(row.taskId)
  }).then(() => {
    ElMessage.success('删除成功')
    fetchTaskList()
  }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
  try {
    await taskFormRef.value.validate()

    const isAdd = form.value.taskId === undefined
    const api = isAdd ? addWorkOrderTask : updateWorkOrderTask

    await api(form.value)
    ElMessage.success('操作成功')
    dialog.visible = false
    fetchTaskList()
  } catch (error) {
    console.error('保存工单任务失败:', error)
  }
}

// 显示批量关联对话框
const showBatchDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  batchDialog.visible = true
  batchDialog.workOrderTemplateId = undefined
}

// 处理批量关联
const handleBatchAssociate = async () => {
  if (!batchDialog.workOrderTemplateId) {
    ElMessage.warning('请选择工单模板')
    return
  }

  try {
    const taskIds = selectedRows.value.map(row => row.taskId)
    await batchAssociateTemplate({
      taskIds,
      workOrderTemplateId: batchDialog.workOrderTemplateId
    })

    ElMessage.success('批量关联成功')
    batchDialog.visible = false
    fetchTaskList()
  } catch (error) {
    console.error('批量关联失败:', error)
    ElMessage.error('批量关联失败')
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mt-2 {
  margin-top: 20px;
}

.el-table {
  margin-top: 10px;
}
</style>